# config11/device.py
import os
import json
import torch
from transformers import pipeline
class DeviceManager:
    _instance = None

    def __new__(cls):
        if not cls._instance:
            cls._instance = super().__new__(cls)
            cls._instance._device = None
        return cls._instance

    def __init__(self):
        if self._device is None:
            self._initialize_device()

    def _initialize_device(self):
        """初始化设备配置"""
        device_config = self._load_config()

        if device_config == "auto":
            self._device = "cuda" if torch.cuda.is_available() else "cpu"
        elif device_config == "cuda":
            if torch.cuda.is_available():
                self._device = "cuda"
            else:
                print("警告：CUDA 不可用，回退到 CPU")
                self._device = "cpu"
        else:
            self._device = device_config

    def _load_config(self):
        """加载配置文件"""
        try:
            # 获取当前模块的绝对路径
            module_dir = os.path.dirname(os.path.abspath(__file__))
            config_path = os.path.join(module_dir, 'config.json')

            with open(config_path, 'r') as f:
                return json.load(f).get("qa_config", {}).get("device", "auto")
        except Exception as e:
            print(f"配置加载错误: {str(e)}，使用默认设备")
            return "auto"

    @property
    def current(self):
        """获取当前设备"""
        return self._device


# 创建全局单例实例
device_manager = DeviceManager()
print(device_manager.current)